package cpczxt;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {
	private static final String APP_TITLE = "成品称重系统";
	private static int LEN = 10000;
	private static final String SYS_URL = "url";
	private static final String LINE_SEPARATOR = System.getProperty("line.separator");
	private ImageIcon image = new ImageIcon(MainFrame.class.getResource("app.png"));
	private ImageIcon image1 = new ImageIcon(MainFrame.class.getResource("start.png"));
	private ImageIcon image2 = new ImageIcon(MainFrame.class.getResource("stop.png"));
	private JButton button1 = new JButton("启动", image1);
	private JButton button2 = new JButton("停止", image2);
	private JComboBox<String> combo1 = new JComboBox<String>();
	private JTextField text2 = new JTextField(15);
	private JTextField text3 = new JTextField(35);
	private JTextArea text = new JTextArea();
	private JPanel panel1 = new JPanel(new GridLayout(2, 1));
	private JPanel panel11 = new JPanel();
	private JPanel panel12 = new JPanel();
	private JPanel panel2 = new JPanel();
	private SerialPort serialPort = null;

	private int ii = 0;

	public MainFrame() {
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (combo1.getSelectedItem() == null) {
					JOptionPane.showMessageDialog(null, "请选择串口");
					return;
				}
				serialPort = RXTXUtils.openSerialPort(combo1.getSelectedItem().toString(), Integer.valueOf(text2.getText()));
				if (serialPort == null) {
					JOptionPane.showMessageDialog(null, "开启串口失败");
					return;
				}
				button1.setEnabled(false);
				button2.setEnabled(true);
				save();
				text.setText("启动成功...");
				text.append(LINE_SEPARATOR);
				RXTXUtils.setListenerToSerialPort(serialPort, new SerialPortEventListener() {
					@Override
					public void serialEvent(SerialPortEvent arg0) {
						if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
							try {
								if (text.getText().length() > LEN) {
									text.setText("");
								}
								byte[] bytes = RXTXUtils.readData(serialPort);
								String s = new String(bytes);
								String ss = s.substring(s.indexOf("*0 ") + 3, s.indexOf("*0 ") + 3 + 12);
								int i = Integer.valueOf(ss) / 1000 / 1000;
								if (i > 0 && i != ii) {
									ii = i;
									text.append(String.valueOf(i));
									text.append(LINE_SEPARATOR);
									String json = HttpUtils.get(text3.getText() + i);
									text.append(json);
									text.append(LINE_SEPARATOR);
									text.setCaretPosition(text.getDocument().getLength());
								}
							} catch (Exception e) {

							}
						}
					}
				});
			}
		});
		button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				RXTXUtils.closeSerialPort(serialPort);
				button1.setEnabled(true);
				button2.setEnabled(false);
				text.append("停止成功...");
			}
		});
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				if (button1.isEnabled()) {
					MainFrame.this.setVisible(false);
					MainFrame.this.dispose();
					System.exit(0);
				}
			}
		});
		combo1.setPreferredSize(text2.getPreferredSize());
		List<String> list = RXTXUtils.getSystemPort();
		for (String s : list) {
			combo1.addItem(s);
		}
		text2.setText("1200");
		text2.setEnabled(false);
		panel12.add(new JLabel("URL接口："));
		panel12.add(text3);
		panel1.add(panel12);
		panel11.add(new JLabel("串口："));
		panel11.add(combo1);
		panel11.add(new JLabel("波特率："));
		panel11.add(text2);
		panel1.add(panel11);
		this.add(panel1, BorderLayout.NORTH);
		text.setRows(10);
		this.add(new JScrollPane(text), BorderLayout.CENTER);
		panel2.add(button1);
		panel2.add(button2);
		this.add(panel2, BorderLayout.SOUTH);
		this.setIconImage(image.getImage());
		this.setTitle(APP_TITLE);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		button2.setEnabled(false);
		load();
	}

	public static void main(String[] args) {
		new MainFrame();
	}

	private void load() {
		try {
			InputStreamReader in = new InputStreamReader(new FileInputStream("sys.ini"), "UTF-8");
			Properties prop = new Properties();
			prop.load(in);
			in.close();
			text3.setText(prop.getProperty(SYS_URL));
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
	}

	private void save() {
		try {
			FileWriter out = new FileWriter("sys.ini");
			out.write(SYS_URL + "=" + text3.getText());
			out.close();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
	}
}